<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- card -->
    <el-card>
      <el-row>
        <el-col :span="1">
          <el-button type="primary" @click="dialogVisible = true">增加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="roleList" border stripe style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <el-row :key="item1.id" v-for="(item1) in scope.row.children" class="bdbotton">
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightByID(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级三级权限    -->
              <el-col :span="19">
                <!-- 二级权限 -->
                <el-row :key="item2.id" v-for="(item2) in item1.children" class="bdbotton">
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightByID(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      :key="item3.id"
                      v-for="item3 in item2.children"
                      closable
                      type="warning"
                      @close="removeRightByID(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色姓名" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editUser(scope.row.id)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteUser(scope.row.id)"
            >删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
        <!-- dialog 对话框 -->
      </el-table>
    </el-card>
    <el-dialog
      :title="flag?'修改角色':'添加角色'"
      :visible.sync="dialogVisible"
      width="30%"
      @close="dialogClosed"
    >
      <!-- 表单 -->
      <el-form :model="getList" label-width="80px" :rules="addRules" ref="getList">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="getList.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="getList.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="addRoleList" :disabled="disabled">确 定</el-button>
      <!-- <el-button type="primary" v-else @click="editRoleList" :disabled="disabled">确 定</el-button> -->
    </el-dialog>

    <!-- 分配权限dialog -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="30%"
      @close="setRightDialogClosed"
    >
      <!--  -->
      <el-tree
        :data="rightList"
        ref="treeRef"
        :props="rightProps"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="expandedKeys"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      flag: false,
      dialogVisible: false,
      //   刷新列表
      roleList: [],
      getList: {
        roleName: '',
        roleDesc: ''
      },
      //   更急id获取列表
      editList: {},
      disabled: false,
      addRules: {
        roleName: [
          { required: true, message: '请输入角色姓名', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ]
      },
      setRightDialogVisible: false,
      rightList: [],
      //
      rightProps: {
        children: 'children',
        label: 'authName'
      },
      expandedKeys: [],
      userRight: '',
      setRoleDialogVisible:false
    }
  },
  methods: {
    //   刷新列表
    async getRoleList() {
      const { data: res } = await this.$http.get('/roles')
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.roleList = res.data
    },
    dialogClosed() {
      this.$refs.getList.resetFields()
      this.getList.roleDesc = ''
    },
    addRoleList() {
      this.$refs.getList.validate(async valid => {
        console.log(valid)
        if (!valid) return this.$message.error('添加失败')
        if (!this.flag) {
          const { data: res } = await this.$http.post('/roles', this.getList)
          console.log(res)
          if (res.meta.status != 201) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
        } else {
          const { data: res } = await this.$http.put(
            '/roles/' + this.editList.roleId,
            {
              roleName: this.getList.roleName,
              roleDesc: this.getList.roleDesc
            }
          )
          if (res.meta.status !== 200) return this.$message.error('修改失败')
        }

        this.getRoleList()
        this.dialogVisible = false
      })
    },
    // 编辑
    async editUser(id) {
      // console.log(id);
      const { data: res } = await this.$http.get('/roles/' + id)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.flag = true
      // 添加列表
      this.editList = res.data
      this.getList.roleName = this.editList.roleName
      this.getList.roleDesc = this.editList.roleDesc
      this.dialogVisible = true
    },
    // 删除
    async deleteUser(id) {
      const val = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(ret => ret)
      console.log(val)
      if (val === 'cancel') return this.$message.info('取消删除')
      const { data: res } = await this.$http.delete('/roles/' + id)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')

      this.getRoleList()
    },
    // 删除权限
    async removeRightByID(user, rightId) {
      const val = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (val !== 'confirm') return this.$message.info('取消删除')
      console.log('success')
      const { data: res } = await this.$http.delete(
        `roles/${user.id}/rights/${rightId}`
      )
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('删除权限失败')
      user.children = res.data
    },
    // 分配权限查询
    async showSetRightDialog(role) {
      const { data: res } = await this.$http.get('/rights/tree ')
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('查询失败')
      this.rightList = res.data
      //    获取角色id
      this.userRight = role.id
      console.log(this.userRight)
      this.getLeafKeys(role, this.expandedKeys)
      this.setRightDialogVisible = true
    },
    getLeafKeys(node, arr) {
      // 如果node节点包含children属性,则是三级节点

      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    setRightDialogClosed() {
      this.expandedKeys = []
    },
    async allotRights() {
      let arr = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      let isStr = arr.join(',')

      const { data: res } = await this.$http.post(
        `roles/${this.userRight}/rights`,
        { rids: isStr }
      )
      // console.log(data);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getRoleList()
      this.setRightDialogVisible = false
    },
 
    
  },
  created() {
    this.getRoleList()
  }
}
</script>
<style lang='css' scoped>
.el-tag {
  margin: 10px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbotton {
  border-bottom: 1px solid #eee;
}
.el-row {
  display: flex;
  align-items: center;
}
</style>